import { ElMessage } from 'element-plus';
import { useRouterStore } from '../store/routerStore';
import { useAuthStore } from '../store/authStore';
import { useUserInfoStore } from '../store/userInfoStore';


import axios from './axios'

/**登录接口 */
export const LoginJwt = async (form) => {
    const result = await axios.post('/Login/LoginJwt', form);

    const autoStore = useAuthStore();

    if (result.statusCode == 200 && result.success == true) {
        //存储菜单
        await GetRoutes()
        //存储登录权限
        autoStore.setAuth(result.response);
        ElMessage.success(result.message);
        return true
    } else {
        autoStore.logout()
        ElMessage.error(result.message);
        return false
    }
}

/**获取路由配置 */
export const GetRoutes = async () => {
    try {
        const routerStore = useRouterStore();
        const result = await axios.post('/RolePermission/GetVueRouterResult',
            { ids: ['1860957227343548416'], all: false });

        if (result.statusCode == 200 && result.success == true) {
            routerStore.setRoutes(result.response);
        }
    } catch (error) {
        console.error('获取路由配置失败:', error);
    }
}

/**获取个人信息 */
export const GetUserInfo = async () => {
    const userInfoStore = useUserInfoStore();

    const result = await axios.get('/User/GetUserCenterInfo');
    if (result.statusCode == 200 && result.success == true) {
        userInfoStore.setUserInfo(result.response);
        return true;
    } else {
        ElMessage.error('获取失败');
        return false;
    }
}

/**修改个人信息 */
export const UpdateUserInfo = async (form) => {
    const result = await axios.post('/User/EditUserCenterAsync', form);
    if (result.statusCode === 200 && result.success === true) {
        ElMessage.success('保存成功');
        return true
    } else {
        ElMessage.error(result.message || '保存失败');
        return false
    }
}

/**渲染动态路由 */
export const dynamicRoutes = async (router) => {
    const routerStore = useRouterStore();
    // 添加动态路由
    const transformedRoutes = transformRoutes(routerStore.routes);

    const homeRoute = router.getRoutes().find(route => route.name === 'home');
    if (homeRoute) {
        // 将动态路由添加到现有的 home 子路由中
        transformedRoutes.forEach(route => {
            router.addRoute('home', route);  // 将动态路由添加到 home 下
        });
    } else {
        console.error('Home route not found, please check the initial routes.');
        return false
    }

    return true;
};

/**动态路由转换 */
export const transformRoutes = (routes) => {
    const modules = import.meta.glob('../views/**/*.vue');
    const default404 = "../views/404.vue";

    return routes.map(route => {
        const componentPath = route.component; // 使用后端返回的完整路径
        // 只处理以 "@/views" 开头的路径
        if (componentPath) {
            const relativePath = componentPath?.replace('@', '..');

            if (modules[relativePath]) {
                route.component = modules[relativePath];  // 匹配到模块时直接加载
            } else {
                route.component = modules[default404];  // 路径无效时指向 404 页面
            }
        }

        // 如果有子路由，递归处理
        if (route.children && route.children.length > 0) {
            route.children = transformRoutes(route.children);
        }

        return route;
    });
};

/**获取Task任务列表 */
export const QueryJobPlans = async () => {
    try {
        const result = await axios.get('/QzJobPlan/QueryJobPlansAsync');
        if (result.statusCode == 200 && result.success == true) {
            return result.response;
        }
    } catch {
        return false
    }
}

/**新增Task任务 */
export const AddJob = async (job) => {
    try {
        const result = await axios.post('/QzJobPlan/AddJobAsync', job);
        if (result.statusCode == 200 && result.success == true) {
            return true;
        }
    } catch {
        return false
    }
}

/**获取task测试日志数据 */
export const QueryTaskTestLogs = async () => {
    try {
        const result = await axios.get('/SysLogs/QueryTaskTestLogsAsync');
        if (result.statusCode == 200 && result.success == true) {
            return result.response;
        }
    } catch {
        return false
    }
}

/**立刻执行一个任务 */
export const ExecuteJob = async (id) => {
    try {
        const result = await axios.get('/QzJobPlan/ExecuteJobAsync?id=' + id);
        if (result.statusCode == 200 && result.success == true) {
            return result.response;
        }
    } catch {
        return false
    }
}

/**删除Job任务 */
export const DeleteJobs = async (ids) => {
    try {
        const result = await axios.post('/QzJobPlan/DeleteJobsAsync', ids);
        if (result.statusCode == 200 && result.success == true) {
            return result.response;
        }
    } catch {
        return false
    }
}

/**编辑Job任务 */
export const EditJob = async (job) => {
    try {
        const result = await axios.post('/QzJobPlan/EditJobAsync', job);
        if (result.statusCode == 200 && result.success == true) {
            return true;
        }
    } catch {
        return false
    }
}

/**启动Job任务 */
export const StartJob = async (id) => {
    try {
        const result = await axios.get('/QzJobPlan/StartJobAsync?id=' + id);
        if (result.statusCode == 200 && result.success == true) {
            ElMessage.success(result.message)
        } else {
            ElMessage.error(result.message)
        }
        return true;
    } catch {
        return false
    }
}

/**停止Job任务 */
export const StopJob = async (id) => {
    try {
        const result = await axios.get('/QzJobPlan/StopJobAsync?id=' + id);
        if (result.statusCode == 200 && result.success == true) {
            ElMessage.success(result.message)
        } else {
            ElMessage.error(result.message)
        }
        return true;
    } catch {
        return false
    }
}

const DbFirst = '/DbFirst/';
/**生成viewModel文件 */
export const CreateViewModelsFile = async (path, nameSpace) => {
    try {
        const result = await axios.get(`${DbFirst}CreateViewModelsFile?path=${path}&nameSpace=${nameSpace}`);
        if (result.statusCode == 200 && result.success == true) {
            ElMessage.success(result.message)
        } else {
            ElMessage.error(result.message)
        }
        return true;
    } catch {
        return false
    }
}

/**生成viewModel文件 */
export const CreateDataTable = async (modelName, filterByNameSpace) => {
    try {
        const result = await axios.get(`${DbFirst}CreateDataTable?modelName=${modelName}&filterByNameSpace=${filterByNameSpace}`);
        if (result.statusCode == 200 && result.success == true) {
            ElMessage.success(result.message)
        } else {
            ElMessage.error(result.message)
        }
        return true;
    } catch {
        return false
    }
}

/**生成业务层文件 */
export const CreateFilesByModels = async (form) => {
    try {
        const result = await axios.post(`${DbFirst}CreateFilesByModels`, form);
        if (result.statusCode == 200 && result.success == true) {
            ElMessage.success(result.message)
        } else {
            ElMessage.error(result.message)
        }
        return true;
    } catch {
        return false
    }
}

/**获取实体名称 */
export const GetModelNames = async () => {
    const result = await axios.get(`${DbFirst}GetModelNames`);
    if (result.statusCode == 200 && result.success == true) {
        // ElMessage.success(result.message)
        return result.response
    } else {
        // ElMessage.error(result.message)
        return [];
    }
}

/**初始化数据 */
export const InitData = async () => {
    const result = await axios.get(`${DbFirst}InitData`,{
        timeout:60000
    });
    if (result.statusCode == 200 && result.success == true) {
        // ElMessage.success(result.message)
        return true
    } else {
        // ElMessage.error(result.message)
        return false;
    }
}

/**校验token */
export const CheckToken = async () => {
    const result = await axios.get(`Login/CheckToken`);
    if (result.statusCode == 200 && result.success == true) {
        return true
    } else {
        return false;
    }
}